using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Win.Models;
using CPlatePrintSys.Win.Views;
using Prism.Commands;
using Prism.Mvvm;

namespace CPlatePrintSys.Win.ViewModels
{
    public class RoundingRuleConfigViewModel : BindableBase
    {
        private readonly IGlobalConfigService _configService;

        // 取整规则列表（用于UI绑定）
        private ObservableCollection<RoundingRuleModel> _roundingRules;
        public ObservableCollection<RoundingRuleModel> RoundingRules
        {
            get { return _roundingRules; }
            set { SetProperty(ref _roundingRules, value); }
        }

        // 取整规则选项
        public List<string> RoundingRuleOptions { get; private set; }

        // 状态
        private bool _isLoading;
        public bool IsLoading
        {
            get { return _isLoading; }
            set { SetProperty(ref _isLoading, value); }
        }

        private string _statusMessage;
        public string StatusMessage
        {
            get { return _statusMessage; }
            set { SetProperty(ref _statusMessage, value); }
        }

        // 命令
        public ICommand AddRuleCommand { get; }
        public ICommand EditRuleCommand { get; }
        public ICommand DeleteRuleCommand { get; }
        public ICommand LoadRulesCommand { get; }

        public RoundingRuleConfigViewModel(IGlobalConfigService configService)
        {
            _configService = configService;

            // 初始化取整规则选项
            RoundingRuleOptions = CPlatePrintSys.Domain.Models.RoundingRuleOptions.GetAllOptions();

            AddRuleCommand = new DelegateCommand(AddRule);
            EditRuleCommand = new DelegateCommand<RoundingRuleModel>(EditRule);
            DeleteRuleCommand = new DelegateCommand<RoundingRuleModel>(DeleteRule);
            LoadRulesCommand = new DelegateCommand(async () => await LoadRulesAsync());

            // 初始化取整规则列表
            RoundingRules = new ObservableCollection<RoundingRuleModel>();

            LoadRulesAsync();
        }

        private async Task LoadRulesAsync()
        {
            try
            {
                IsLoading = true;
                StatusMessage = "正在加载取整规则...";

                var config = await _configService.GetRoundingRuleConfigAsync();
                
                // 清空现有规则
                RoundingRules.Clear();
                
                // 添加默认规则
                RoundingRules.Add(new RoundingRuleModel
                {
                    RuleName = "默认规则",
                    RoundingMethod = config.Default,
                    IsDefault = true
                });
                
                // 添加各阶段规则
                foreach (var stage in config.Stages)
                {
                    RoundingRules.Add(new RoundingRuleModel
                    {
                        RuleName = stage.Key,
                        RoundingMethod = stage.Value,
                        IsDefault = false
                    });
                }
                
                StatusMessage = "取整规则加载完成";
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载取整规则失败: {ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void AddRule()
        {
            try
            {
                var viewModel = new RoundingRuleAddOrEditViewModel(_configService, null, OnRuleSaved);
                var view = new RoundingRuleAddOrEditView
                {
                    DataContext = viewModel,
                    Owner = System.Windows.Application.Current.MainWindow
                };
                
                // 订阅关闭窗口事件
                viewModel.CloseWindowRequested += () => view.Close();
                
                view.ShowDialog();
            }
            catch (Exception ex)
            {
                StatusMessage = $"打开添加规则对话框失败: {ex.Message}";
            }
        }

        private void EditRule(RoundingRuleModel rule)
        {
            if (rule == null) return;
            
            try
            {
                var viewModel = new RoundingRuleAddOrEditViewModel(_configService, rule, OnRuleSaved);
                var view = new RoundingRuleAddOrEditView
                {
                    DataContext = viewModel,
                    Owner = System.Windows.Application.Current.MainWindow
                };
                
                // 订阅关闭窗口事件
                viewModel.CloseWindowRequested += () => view.Close();
                
                view.ShowDialog();
            }
            catch (Exception ex)
            {
                StatusMessage = $"打开编辑规则对话框失败: {ex.Message}";
            }
        }

        private async void OnRuleSaved(RoundingRuleModel savedRule)
        {
            try
            {
                // 重新加载规则列表
                await LoadRulesAsync();
                StatusMessage = $"规则保存成功: {savedRule.RuleName}";
            }
            catch (Exception ex)
            {
                StatusMessage = $"重新加载规则失败: {ex.Message}";
            }
        }

        private async void DeleteRule(RoundingRuleModel rule)
        {
            if (rule == null) return;
            
            if (rule.IsDefault)
            {
                StatusMessage = "默认规则不能删除";
                return;
            }

            // 显示删除确认对话框
            var result = MessageBox.Show(
                $"删除后将不可恢复，您确认删除规则 \"{rule.RuleName}\" 吗？", 
                "确认删除", 
                MessageBoxButton.OKCancel, 
                MessageBoxImage.Warning);
            
            if (result != MessageBoxResult.OK)
            {
                return;
            }

            try
            {
                IsLoading = true;
                StatusMessage = "正在删除规则...";

                var config = await _configService.GetRoundingRuleConfigAsync();
                if (config.Stages.ContainsKey(rule.RuleName))
                {
                    config.Stages.Remove(rule.RuleName);
                    await _configService.UpdateRoundingRuleConfigAsync(config, "System");
                    
                    RoundingRules.Remove(rule);
                    StatusMessage = $"已删除规则: {rule.RuleName}";
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"删除规则失败: {ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }
    }
} 